package com.huluobo.jetpackkotlindemo2006a.coroutine

import android.os.Bundle
import android.util.Log
import androidx.lifecycle.lifecycleScope
import com.google.gson.Gson
import com.huluobo.jetpackkotlindemo2006a.databinding.ActivityRetrofitBinding
import com.huluobo.jetpackkotlindemo2006a.viewbinding.BaseActivity
import kotlinx.coroutines.*
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

/**
 * Created by lc on 2023/2/22.
 */
class RetrofitActivity : BaseActivity<ActivityRetrofitBinding>() {
    override fun getViewBinding(): ActivityRetrofitBinding =
        ActivityRetrofitBinding.inflate(layoutInflater)

    private val retrofit = Retrofit.Builder().baseUrl("https://api.github.com/")
        .addConverterFactory(GsonConverterFactory.create()).build()

    private val apiService = retrofit.create(ApiService::class.java)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

//        apiService.queryData().enqueue(object : Callback<List<User>> {
//            override fun onResponse(call: Call<List<User>>?, response: Response<List<User>>?) {
//                mViewBinding.tvText.text = Gson().toJson(response?.body())
//            }
//
//            override fun onFailure(call: Call<List<User>>?, t: Throwable?) {
//                Log.i("TagA", "t:${t.toString()}")
//            }
//        })

        //使用协程来发起网络请求
        //retrofit2.9可以直接支持在main中调用协程来进行线程的切换
        val job = Job()
        CoroutineScope(job).launch(Dispatchers.Main) {
            val result = apiService.queryData1()
            mViewBinding.tvText.text = Gson().toJson(result)
        }

        //如果retrofit2.8以下 不支持直接在main线程中调用,则需要协程的切换
//        CoroutineScope(job).launch(Dispatchers.Main) {
//            val result = withContext(Dispatchers.IO) {
//                apiService.queryData1()
//            }
//            mViewBinding.tvText.text = Gson().toJson(result)
//        }

        //会把协程绑定到当前的lifecycle对象上
        lifecycleScope.launchWhenCreated {
            Log.i("TagA","launchWhenCreated")
        }

        lifecycleScope.launchWhenResumed {
            Log.i("TagA","launchWhenResumed")
        }

        lifecycleScope.launchWhenStarted {
            Log.i("TagA","launchWhenStarted")
        }
    }
}